package com.shop.wk.controller;

import com.shop.wk.common.constant.HttpCode;
import com.shop.wk.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 日月星辰
 * @date 2020/12/25 0:01
 * @description
 */
@Slf4j
@Api(value = "用户相关", tags = "UserApi")
@RestController
@RequestMapping("/auth")
public class UserController {

	@Autowired
	private ConsumerTokenServices consumerTokenServices;

	@ApiOperation(value = "获取用户信息")
	@GetMapping("/user")
	public Authentication getUser(Authentication authentication) {
		log.info("resource: user {}", authentication);
		return authentication;
	}

	@ApiOperation(value = "获取账号信息")
	@GetMapping("/getUser")
	public Principal user(Principal member) {
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		System.out.println(name);
		// 获取当前用户信息
		return member;
	}

	@ApiOperation(value = "注销用户")
	@GetMapping("/user/logout")
	public ResponseResult<Void> logout(HttpServletRequest request) {
		// 获取 token
		String token = request.getParameter("access_token");
		if (token == null) {
			token = request.getHeader("authorization").split(" ")[1];
		}
		// 删除 token 以注销
		consumerTokenServices.revokeToken(token);
		return new ResponseResult<Void>(HttpCode.OK, "注销成功");
	}

}
